package com.bakend.common.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.bakend.common.R;
import com.bakend.common.config.security.login.CustomerUserDetails;
import com.bakend.common.utils.HttpUtils;
import com.bakend.common.utils.JwtUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.tomcat.util.http.ResponseUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录成功后进入这里进行后续处理,获取该用户对应的权限信息，生成token返回给客户端
 */
@Component
public class CustomerAuthenticationSuccessHandler implements AuthenticationSuccessHandler {


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        CustomerUserDetails principal = (CustomerUserDetails) authentication.getPrincipal();


        //简单的说就是获取当前用户，拿到用户名或者userId，创建token，返回
//

//        //颁发token
        Map<String, Object> emptyMap = principal.toClaimMap();
        emptyMap.put(JwtUtils.UserIdKey, principal.getId());
        String token = JwtUtils.generateToken(emptyMap);
        R r = new R().setMsg("登录成功").setData(token);
        HttpUtils.reponseJson(r);
    }

}
